package interpreter;

import edu.rice.cs.dynamicjava.interpreter.EvaluatorException;
import edu.rice.cs.dynamicjava.interpreter.Interpreter;
import edu.rice.cs.dynamicjava.interpreter.InterpreterException;
import edu.rice.cs.plt.reflect.ReflectUtil;
import edu.rice.cs.plt.text.TextUtil;
import edu.rice.cs.plt.tuple.Option;

/**
 * @author WL
 */
public class JavaInterpreter 
{
    private volatile InteractionsPaneOptions _interpreterOptions;
    private volatile edu.rice.cs.dynamicjava.interpreter.Interpreter _interpreter;
    private volatile ClassLoader _interpreterLoader;
  
    public JavaInterpreter()
    {
        this(null, null);
    }
    
    public JavaInterpreter(ClassLoader loader)
    {
        this(null, loader);
    }
    
    public JavaInterpreter(InteractionsPaneOptions options, ClassLoader loader)
    {
        _interpreterOptions = (options == null) ? new InteractionsPaneOptions() : options;
        _interpreterLoader = (loader == null) ? new ClassPathManager(ReflectUtil.SYSTEM_CLASS_PATH).makeClassLoader(null) : 
                loader;
        _interpreter = new Interpreter(_interpreterOptions, _interpreterLoader);
            
    }
    
    public String interpret(String code) throws InterpreterException
    {
        Option<Object> result = _interpreter.interpret(code);
        if (result.isSome()) {
            String objString = null;
            try { objString = TextUtil.toString(result.unwrap()); }
            catch (Throwable t) { throw new EvaluatorException(t); }
            return objString;
        }
       return "";
    }
}
